package com.hunantv.mglive.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.data.login.UserInfoData;

/**
 * Created by admin on 2015/12/24.
 */
public class TokenPreference {
    private Object object = new Object();
    private static TokenPreference tokenPreference;
    private SharedPreferences sharedPreferences;
    private static final String TOKEN_KEY = "token_info";

    public static TokenPreference getInstance(Context context) {
        if (tokenPreference == null) {
            tokenPreference = new TokenPreference(context);
        }
        return tokenPreference;
    }

    private TokenPreference(Context context) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName() + "token_info", Context.MODE_PRIVATE);
    }

    public void saveToken(UserInfoData userInfo) {
        synchronized (object) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(TOKEN_KEY, JSON.toJSONString(userInfo));
            L.d("TokenPreference Save Token", JSON.toJSONString(userInfo));
            editor.apply();
        }
    }

    public void removeToken() {
        synchronized (object) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.remove(TOKEN_KEY);
            editor.apply();
        }
    }

    public UserInfoData getUserInfo() {
        synchronized (object) {
            String infoJson = sharedPreferences.getString(TOKEN_KEY, "");
            L.d("TokenPreference Get Info", infoJson);
            return StringUtil.isNullorEmpty(infoJson) ? null : JSON.parseObject(infoJson, UserInfoData.class);
        }
    }
}
